//
//  AppDelegate.swift
//  Weibo
//
//  Created by cc on 11/07/2017.
//  Copyright © 2017 cc. All rights reserved.
//

import UIKit
import UserNotifications
import SVProgressHUD
import AFNetworking


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        //應用程序額外設置
        setupAdditions()
       
        
        window = UIWindow()
        window?.backgroundColor = UIColor.white
        window?.rootViewController = WBMainViewController()
        window?.makeKeyAndVisible()
        
        loadAppInfo()
        
        return true
    }

}


// MARK: - 設置應用程序額外信息
extension AppDelegate {
    private func setupAdditions() {
        //1.設置 SVProguressHUD 最小解除時間
        SVProgressHUD.setMinimumDismissTimeInterval(1)
        
        //2.設置網絡加載指示器
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
        
        //3.設置用戶授權顯示通知
        //  #available  10.0 以上
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .carPlay, .sound]) { (success, error) in
                print("授权 " + (success ? "成功" : "失败"))
            }
        } else {
            // 10.0 以下
            //取得用户授权显示通知[上方提示条/ 声音/BadgeNumber]
            let notifySetting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(notifySetting)
        }
        
    }
}

// MARK: - 从服务器加载应用程序信息
extension AppDelegate {
    private func loadAppInfo() {
        //1. 模拟异步
        DispatchQueue.global().async {
            //1.> URL
            let url = Bundle.main.url(forResource: "main.json", withExtension: nil)
            
            //2.> data
            let data = NSData(contentsOf: url!)
            
            //3. 写入磁盘
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
            
            //直接保存在沙盒中，等待下一次程序启动使用
            data?.write(toFile: jsonPath, atomically: true)
            
            
            print("应用程序加载完毕，\(jsonPath)")
        }
        
    }
}
